package com.books.controller.admin;

import com.books.model.bo.Result;
import com.books.model.dto.BuyOrderDto;
import com.books.model.entity.backcontroller.Admin;
import com.books.model.entity.backcontroller.Announcement;
import com.books.model.entity.backcontroller.Chat;
import com.books.model.entity.backcontroller.Vip;
import com.books.model.entity.address.Receiving_address;
import com.books.model.entity.back.Back;
import com.books.model.entity.book.BookType;
import com.books.model.entity.book.Books;
import com.books.model.entity.book.Ebook;
import com.books.model.entity.common.People;
import com.books.model.entity.hotrecommend.Digest;
import com.books.model.entity.login_regis.UserLogin;
import com.books.model.entity.order.BackTool;
import com.books.model.entity.order.BuyOrder;
import com.books.model.entity.order.OrderList;
import com.books.model.tool.*;
import com.books.service.address.IAddressService;
import com.books.service.admin.IAdminService;
import com.books.service.hotrecommend.IDigestService;
import com.books.service.login_regis.IUserLoginService;
import com.books.service.page.PageService;
import com.books.service.people.IPeopleService;
import com.books.service.searchimg.DownloadPicFromUrl;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @Author 饿熊的咆哮
 * @Date 2021/9/24 18:05
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @Autowired
    private PageService pageService;

    @Autowired
    private IUserLoginService iUserLoginService;

    @Autowired
    private IDigestService digestService;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IPeopleService peopleService;


    /**
     * 后台登录主界面
     * @return
     */
    @GetMapping("/login")
    public String login(){
        return "admin/login";
    }

    @PostMapping("/logincl")
    @ResponseBody
    public Result logincl(Admin admin){
        //1. 调用根据用户查找的方法
        Admin a = adminService.findByAccount(admin.getAccount());
        if(a==null){
            return new Result("404","账号不存");
        }
        if(a.getPassword().equals(admin.getPassword())){
            return new Result("200","登录成功");
        }
        return new Result("500","密码错误");
    }



    @GetMapping("/getAdminName")
    @ResponseBody
    public Result getAdminName(String account){
        Admin admin = adminService.findByAccount(account);
        return new Result("200","查询成功",admin);
    }

    /**
     * 重要的方法,通过账号获取整个管理员
     * @param account
     * @return
     */
    @GetMapping("/getAdminByAccount")
    @ResponseBody
    public Admin getAdminByAccount(String account){
        Admin admin = adminService.findByAccount(account);
        return admin;
    }

    //----------跳到管理端开始
    @GetMapping("/EChat")
    public String EChat(Model model){
        List<Data> vipNum = adminService.findVipNum();
        JSONArray jsonVipNum = JSONArray.fromObject(vipNum);
        model.addAttribute("vipNum",jsonVipNum);
        List<MonthPriceTool> monthPriceTools = adminService.getMonthMoney();
        if (monthPriceTools.size()>=6){
            monthPriceTools = monthPriceTools.subList(0, 6);
        }
        Collections.reverse(monthPriceTools);
        JSONArray month = JSONArray.fromObject(monthPriceTools);
        List<String> name = new ArrayList<>();
        for (Data data : vipNum) {
            name.add(data.getName());
        }
        JSONArray jsonName = JSONArray.fromObject(name);
        model.addAttribute("name",jsonName);
        model.addAttribute("monthPrice",month);
        return "admin/in-admin/首页";
    }

    @GetMapping("/admin")
    public String admin(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        People people = adminService.findByPhone(account);
        model.addAttribute("people",people);
        return "admin/admin";
    }

    @GetMapping("/getImgUrl")
    @ResponseBody
    public String getImgUrl(String account){
        String imgUrl = adminService.findByPhone(account).getHeadUrl();
        return imgUrl;
    }

    @PostMapping("/changeImg")
    @ResponseBody
    public Result changeImg(@RequestParam("account") String account, @RequestParam("file") MultipartFile file, HttpServletRequest request){
        People people = adminService.findByPhone(account);
        //获取属性
        String filename = file.getOriginalFilename();
        //重新生成一个新的名称
        String newFileName = UUID.randomUUID().toString()+"_"+filename;
        people.setHeadUrl(newFileName);
        peopleService.change(people,people.getPeopleId());
        //获取imgs的绝对路径
        ///Users/admin/Documents/success/teaching/wksp/spring-j13/springboot-j03s/src/main/webapp/
        String path = request.getServletContext().getRealPath("/");

        //写出去
        File f = new File(path+"imgs/"+newFileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {

            e.printStackTrace();
            return new Result("500","文件上传失败");
        }
        return new Result("200","修改头像成功");
    }

    @GetMapping("/getChat")
    @ResponseBody
    public JSONArray getChat(String account){
        Integer peopleId = adminService.findByPhone(account).getPeopleId();
        //未阅读
        List<Chat> chats = adminService.findRead(peopleId,false);
        JSONArray chatJson = JSONArray.fromObject(chats);
        return chatJson;
    }

    //***************此处未完善,User还没好,用Admin替代---------已完善
    @GetMapping("/getSendPeopleId")
    @ResponseBody
    public Object getSendPeopleId(Integer sendPeopleId){

        Admin admin =adminService.findAdminByPeopleId(sendPeopleId);
        if (admin!=null){
            return admin;
        }else {
            String phone = adminService.findByPeopleId(sendPeopleId).getPhone();
            UserLogin userLogin = iUserLoginService.loginByAccount(phone);
            if (userLogin != null) {
                User user = new User();
                user.setPeopleId(sendPeopleId);
                user.setNickName(userLogin.getUname());
                user.setAccount(phone);
                return user;
            }
            return null;
        }
    }

    @GetMapping("/sendReply")
    @ResponseBody
    public Result sendReply(Integer chatId,String takePeopleAccount,String sendPeopleAccount,String chat,String sendTime){
        Integer takePeopleId = adminService.findByPhone(takePeopleAccount).getPeopleId();
        Integer sendPeopleId = adminService.findByPhone(sendPeopleAccount).getPeopleId();
        Chat sendChat = new Chat();
        sendChat.setSendPeopleId(sendPeopleId);
        sendChat.setTakePeopleId(takePeopleId);
        sendChat.setChat(chat);
        sendChat.setSendTime(sendTime);
        adminService.addChat(sendChat);
        adminService.updateChat(true,chatId);
        return new Result("200","发送成功");
    }

    @GetMapping("/notReply")
    @ResponseBody
    public Result notReply(Integer chatId){
        adminService.updateChat(true,chatId);
        return new Result("200","忽略成功");
    }

    //***************此处未完善,User还没好,用Admin替代---------已完善
    @GetMapping("/historyChat")
    @ResponseBody
    public JSONArray historyChat(String adminAccount,String userAccount){
        Integer adminPeopleId = adminService.findByPhone(adminAccount).getPeopleId();
        People p = adminService.findByPhone(userAccount);
        if (p!=null){
            Integer userPeopleId = adminService.findByPhone(userAccount).getPeopleId();
            List<Chat> chats = adminService.findHistoryChat(adminPeopleId,userPeopleId);
            JSONArray historyChat = JSONArray.fromObject(chats);
            return historyChat;
        }else {
            return null;
        }
    }


    @PostMapping("/savePeople")
    @ResponseBody
    public Result savePeople(People people){
        String phone = people.getPhone();
        People people1 = adminService.findByPhone(phone);
        people.setHeadUrl(people1.getHeadUrl());
        people.setVipId(people1.getVipId());
        adminService.updateByPeopleId(people,people1.getPeopleId());
        return new Result("200","保存成功");
    }

    @PostMapping("/findInf")
    @ResponseBody
    public People findInf(String account){
        People people = adminService.findByPhone(account);
        return people;
    }

    @PostMapping("/changePassword")
    @ResponseBody
    public String changePassword(String account){
        Admin admin = adminService.findByAccount(account);
        return admin.getPassword();
    }

    @PostMapping("/newPassword")
    @ResponseBody
    public Result newPassword(String account,String newpassword){
        Admin admin = adminService.findByAccount(account);
        admin.setPassword(newpassword);
        adminService.updateByAccount(admin,account);
        return new Result("200","密码修改成功!请重新登录");
    }

    @GetMapping("/changeNickName")
    @ResponseBody
    public Result changeNickName(String account,String newNickName){
        Admin admin = adminService.findByAccount(account);
        admin.setNickName(newNickName);
        adminService.updateByAccount(admin,account);
        return new Result("200","昵称修改成功!");
    }


    //----------跳到管理端结束


    @GetMapping("/in_admin/rim")
    public String rim(){
        return "admin/in-admin/轮播图";
    }

    @GetMapping("/in_admin/class_type")
    public String classType(){
        return "admin/in-admin/课程类别表";
    }

    //------------------热门书摘开始


    @GetMapping("/findAllHot")
    public String findAllHot(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Digest> digests = digestService.findAll();
        List<Digest> pageDigests = pageService.findList(digests,8,1);
        int allPage = pageService.findAllPage(digests,8);
        int haveDigests = digests.size();
        JSONArray pageDigestsJson = JSONArray.fromObject(pageDigests);
        model.addAttribute("digests",pageDigestsJson);
        model.addAttribute("allPageDigests",allPage);
        model.addAttribute("haveDigests",haveDigests);
        model.addAttribute("admin",admin);

        return "admin/in-admin/热门书摘";
    }

    @GetMapping("/getNowDigests")
    @ResponseBody
    public JSONArray getNowDigests(Integer nowPage){
        List<Digest> digests = digestService.findAll();
        List<Digest> pageDigests = pageService.findList(digests,8,nowPage);
        JSONArray nowDigests = JSONArray.fromObject(pageDigests);
        return nowDigests;
    }

    @GetMapping("/delOneDigest")
    @ResponseBody
    public Result delOneDigest(Integer delDigestId){
        digestService.delByContentId(delDigestId);
        return new Result("200","删除成功");
    }

    @GetMapping("/addDigests")
    @ResponseBody
    public Result addDigests(String text,String type){
        Digest digest = new Digest(null,text,type);
        digestService.addDigest(digest);
        return new Result("200","添加成功");
    }

    @GetMapping("/findBookCopyByType")
    @ResponseBody
    public JSONArray findBookCopyByType(String findType){
        List<Digest> digests = digestService.findByClassify(findType);
        JSONArray digestJson = JSONArray.fromObject(digests);
        return digestJson;
    }

    //--------------------热门书摘结束

    //-----------------------订单表开始
    @GetMapping("/getAllList")
    public String shopList(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<BuyOrder> buyOrders = adminService.getAllOrders();
        List<BuyOrder> firstPage = pageService.findList(buyOrders,12,1);
        List<BuyOrderDto> buyOrderUtils = new ArrayList<> ();
        for (BuyOrder order : firstPage) {
            String address = addressService.findById (order.getAddressId ()).getAddress ();
            BuyOrderDto buyOrderUtil = new BuyOrderDto (order.getBuyId (),order.getUserId (),order.getBuyTime (),order.getStateId (),order.getPayId (),address,order.getTotalMoney ());
            buyOrderUtils.add (buyOrderUtil);
        }
        JSONArray jsonArray = JSONArray.fromObject (buyOrderUtils);
        int allPage = pageService.findAllPage(buyOrders,12);
        int allOrders = buyOrders.size();
        model.addAttribute("firstPage",jsonArray);
        model.addAttribute("allPage",allPage);
        model.addAttribute("allOrders",allOrders);
        model.addAttribute("admin",admin);
        return "admin/in-admin/订单表";
    }

    @GetMapping("/getNowOrders")
    @ResponseBody
    public JSONArray getNowOrders(int nowPage){
        List<BuyOrder> buyOrders = adminService.getAllOrders();
        List<BuyOrder> page = pageService.findList(buyOrders,12,nowPage);
        List<BuyOrderDto> buyOrderUtils = new ArrayList<> ();
        for (BuyOrder order : page) {
            String address = addressService.findById (order.getAddressId ()).getAddress ();
            BuyOrderDto buyOrderUtil = new BuyOrderDto (order.getBuyId (),order.getUserId (),order.getBuyTime (),order.getStateId (),order.getPayId (),address,order.getTotalMoney ());
            buyOrderUtils.add (buyOrderUtil);
        }
        JSONArray jsonArray = JSONArray.fromObject (buyOrderUtils);
        return jsonArray;
    }

    @GetMapping("/findOrder")
    @ResponseBody
    public JSONArray findOrder(BuyOrder buyOrder){
        List<BuyOrder> buyOrders = adminService.findBy(buyOrder);
        if (buyOrders!=null&&buyOrders.size()>0&&buyOrders.get(0)!=null){
            List<BuyOrderDto> buyOrderUtils = new ArrayList<> ();
            for (BuyOrder order : buyOrders) {
                String address = addressService.findById (order.getAddressId ()).getAddress ();
                BuyOrderDto buyOrderUtil = new BuyOrderDto (order.getBuyId (),order.getUserId (),order.getBuyTime (),order.getStateId (),order.getPayId (),address,order.getTotalMoney ());
                buyOrderUtils.add (buyOrderUtil);
            }
            JSONArray jsonArray = JSONArray.fromObject (buyOrderUtils);
            return jsonArray;
        }else {
            return null;
        }
    }

    @GetMapping("/getOrderList")
    @ResponseBody
    public JSONArray getOrderList(String buyId){
        List<OrderList> orderLists = adminService.findAllList(buyId);
        JSONArray jsonArray = JSONArray.fromObject(orderLists);
        return jsonArray;
    }

    @GetMapping("/updateOrderList")
    @ResponseBody
    public Result updateOrderList(String id,Integer statusId){
        adminService.updateBuyStatus(statusId,id);
        return new Result("200","修改成功");
    }

    //----------------------订单表结束

    //----------------------退款申请表开始

    @GetMapping("/getAllBack")
    public String getAllBack(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        model.addAttribute("admin",admin);
        List<Back> backs = adminService.findAllBack();
        List<Back> pageBack = pageService.findList(backs,12,1);
        List<BackTool> backTools = new ArrayList<>();
        for (Back back : pageBack) {
            OrderList orderList = adminService.findList(back.getOrderListId());
            String shopType = "";
            if (orderList.getBuyType()==1){
                shopType="实体书";
            }else if (orderList.getBuyType()==2){
                shopType="电子书";
            }
            BackTool backTool = new BackTool(orderList.getBuyId(),orderList.getId(),orderList.getProductId(),shopType,back.getPeopleId(),back.getBackTime(),back.getBackReason());
            backTools.add(backTool);
        }
        JSONArray jsonArray = JSONArray.fromObject(backTools);
        int page = pageService.findAllPage(backs,12);
        int allNum = backs.size();
        model.addAttribute("backList",jsonArray);
        model.addAttribute("page",page);
        model.addAttribute("allNum",allNum);
        return "admin/in-admin/退款申请表";
    }

    @GetMapping("/getNowBack")
    @ResponseBody
    public JSONArray getNowBack(int nowPage){
        List<Back> backs = adminService.findAllBack();
        List<Back> pageBack = pageService.findList(backs,12,nowPage);
        List<BackTool> backTools = new ArrayList<>();
        for (Back back : pageBack) {
            OrderList orderList = adminService.findList(back.getOrderListId());
            String shopType = "";
            if (orderList.getBuyType()==1){
                shopType="实体书";
            }else if (orderList.getBuyType()==2){
                shopType="电子书";
            }
            BackTool backTool = new BackTool(orderList.getBuyId(),orderList.getId(),orderList.getProductId(),shopType,back.getPeopleId(),back.getBackTime(),back.getBackReason());
            backTools.add(backTool);
        }
        JSONArray jsonArray = JSONArray.fromObject(backTools);
        return jsonArray;
    }

    @GetMapping("/findBack")
    @ResponseBody
    public JSONArray findBack(String buyId,Integer userId){
        List<Back> backs = adminService.findAllBack();
        List<BackTool> backTools = new ArrayList<>();
        for (Back back : backs) {
            OrderList orderList = adminService.findList(back.getOrderListId());
            String shopType = "";
            if (orderList.getBuyType()==1){
                shopType="实体书";
            }else if (orderList.getBuyType()==2){
                shopType="电子书";
            }
            BackTool backTool = new BackTool(orderList.getBuyId(),orderList.getId(),orderList.getProductId(),shopType,back.getPeopleId(),back.getBackTime(),back.getBackReason());
            backTools.add(backTool);
        }
        List<BackTool> search = new ArrayList<>();
        if (buyId!=null&&buyId.length()!=0){
            for (BackTool backTool : backTools) {
                if (backTool.getOrderId().equals(buyId)){
                    search.add(backTool);
                }
            }
            return JSONArray.fromObject(search);
        }else if (userId!=null){
            for (BackTool backTool : backTools) {
                if (backTool.getUserId()==userId){
                    search.add(backTool);
                }
            }
            return JSONArray.fromObject(search);
        }else {
            return null;
        }
    }

    @GetMapping("/passBack")
    @ResponseBody
    public Result passBack(String orderListId){
        adminService.delByBackId(orderListId);
        adminService.updateBuyStatus(5,orderListId);
        return new Result("200","操作成功");
    }

    @GetMapping("/failBack")
    @ResponseBody
    public Result failBack(String orderListId){
        adminService.delByBackId(orderListId);
        adminService.updateBuyStatus(2,orderListId);
        return new Result("200","操作成功");
    }

    //-----------------退款申请表结束

    //-----------------管理员开始

    @GetMapping("/getAllAdmin")
    public String getAllAdmin(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Admin> adminList = adminService.findAll();
        List<Admin> pageAdmin = pageService.findList(adminList,12,1);
        int allPage = pageService.findAllPage(adminList,12);
        int haveAdmin = adminList.size();
        String AdminJson = JSONArray.fromObject(pageAdmin).toString();
        // System.out.println(AdminJson);
        model.addAttribute("admin",admin);
        model.addAttribute("admins",AdminJson);
        model.addAttribute("allPage",allPage);
        model.addAttribute("haveAdmin",haveAdmin);
        return "admin/in-admin/管理员表";
    }

    @GetMapping("/getNowPage")
    @ResponseBody
    public JSONArray getNowPage(int nowPage){
        List<Admin> adminList = adminService.findAll();
        List<Admin> pageAdmin = pageService.findList(adminList,12,nowPage);
        JSONArray AdminJson = JSONArray.fromObject(pageAdmin);
        return AdminJson;
    }

    @GetMapping("/delOneAdmin")
    @ResponseBody
    public Result delOneAdmin(int delAdminId){
        // System.out.println(delAdminId);
        int peopleId = adminService.findByAdminId(delAdminId).getPeopleId();
        adminService.delByAdminId(delAdminId);
        adminService.delByPeopleId(peopleId);
        adminService.delChat(peopleId);

        return new Result("200","删除成功");
    }

    @PostMapping("/addAdmin")
    @ResponseBody
    public Result addAdmin(Admin admin){
        // System.out.println(admin.getPassword());
        // System.out.println(admin);
        Admin admin1 = adminService.findByAccount(admin.getAccount());
        if (admin1==null){
            //双重添加
            adminService.addAdmin(admin);
            People people = new People();
            people.setPhone(admin.getAccount());
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            people.setRegistrationTime(calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH)+" "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
            people.setIfAdmin(true);
            people.setVipId(-1);
            people.setVipIntegral(-1.0);
            adminService.addPeople(people);
            int peopleId = adminService.findByPhone(people.getPhone()).getPeopleId();
            admin.setPeopleId(peopleId);
            adminService.updateByAccount(admin,admin.getAccount());
            return new Result("200","添加成功");
        }else {
            return new Result("500","抱歉,账号已存在!");
        }

    }

    @PostMapping("/findAdmin")
    @ResponseBody
    public JSONArray findAdmin(String account,String nickName){
        List<Admin> adminList = new ArrayList<>();
        if (account==null){
            adminList = adminService.findByNickName(nickName);
        }else if (nickName==null){
            Admin admin = adminService.findByAccount(account);
            if (admin==null){
                return null;
            }
            adminList.add(admin);
        }
        JSONArray AdminJson = JSONArray.fromObject(adminList);
        return AdminJson;
    }

    @PostMapping("/updatePower")
    @ResponseBody
    public Result updatePower(int uPower,String fAccount){
        Admin admin = adminService.findByAccount(fAccount);
        admin.setPowerId(uPower);
        adminService.updateByAccount(admin,fAccount);
        return new Result("200","修改成功");
    }

    //------------------管理员结束


    //------------------电子书信息表开始

    @GetMapping("/findAllEBook")
    public String ebookInf(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Ebook> ebooks = adminService.findAllEBook();
        List<Ebook> pageEBooks = pageService.findList(ebooks,7,1);
        List<String> category = new ArrayList<>();
        for (Ebook pageEBook : pageEBooks) {
            int typeId = pageEBook.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            category.add(name);
        }
        int allPage = pageService.findAllPage(ebooks,7);
        int haveEBooks = ebooks.size();
        JSONArray pageBooksJson = JSONArray.fromObject(pageEBooks);
        JSONArray categoryJson = JSONArray.fromObject(category);
        model.addAttribute("admin",admin);
        model.addAttribute("ebook",pageBooksJson);
        model.addAttribute("category",categoryJson);
        model.addAttribute("allEBook",allPage);
        model.addAttribute("haveEBooks",haveEBooks);
        return "admin/in-admin/电子书信息表";
    }

    @GetMapping("/getNowEBook")
    @ResponseBody
    public Result getNowEBook(Integer nowPage){
        List<Ebook> ebooks = adminService.findAllEBook();
        List<Ebook> pageEBooks = pageService.findList(ebooks,7,nowPage);
        List<String> category = new ArrayList<>();
        for (Ebook pageEBook : pageEBooks) {
            int typeId = pageEBook.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            category.add(name);
        }

        JSONArray pageBooksJson = JSONArray.fromObject(pageEBooks);
        JSONArray categoryJson = JSONArray.fromObject(category);

        List<JSONArray> list = new ArrayList<>();
        list.add(pageBooksJson);
        list.add(categoryJson);
        return new Result("200","分页成功",list);
    }

    @GetMapping("/updateEBook")
    @ResponseBody
    public Result updateEBook(Integer ebookId,Double price){
        adminService.updateEBook(ebookId,price);
        return new Result("200","修改成功");
    }

    @PostMapping("/findEBook")
    @ResponseBody
    public Result findEBook(String title,String author,String category) {
        Ebook ebook = new Ebook();
        ebook.setTitle(title);
        ebook.setAuthor(author);
        if (category != null) {
            Integer typeId = adminService.findByCategoryName(category).getCategoryId();
            ebook.setCategoryId(typeId);
        }

        List<String> categorys = new ArrayList<>();
        List<Ebook> ebooksList = adminService.findByEBook(ebook);
        for (Ebook eb : ebooksList) {
            int typeId = eb.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            categorys.add(name);
        }

        JSONArray booksListJson = JSONArray.fromObject(ebooksList);
        JSONArray categoryJson = JSONArray.fromObject(categorys);

        List<JSONArray> list = new ArrayList<>();
        list.add(booksListJson);
        list.add(categoryJson);
        return new Result("200", "查询成功", list);
    }

    @PostMapping("/addEBook")
    @ResponseBody
    public Result addEBook(EBookTool ebookTool,HttpServletRequest request){
        Integer typeId = adminService.findByCategoryName(ebookTool.getCategory()).getCategoryId();
        Ebook ebook = new Ebook(null,ebookTool.getTitle(),ebookTool.getPrice(),ebookTool.getAuthor(),ebookTool.getDate(),ebookTool.getPictureUrl(),typeId);
        adminService.addEBook(ebook);
        List<Ebook> ebooks = adminService.findByEBook(ebook);
        Integer ebookId = ebooks.get(0).getEbkId();
        String samePath = request.getServletContext().getRealPath("/");
        String path = samePath+"ebookImg/"+ebookId+".jpg";
        DownloadPicFromUrl.downloadPicture(ebook.getPictureUrl(),path);
        return new Result("200","添加成功");
    }

    @GetMapping("delOneEBook")
    @ResponseBody
    public Result delOneEBook(Integer delEBookId){
        adminService.delByEBkId(delEBookId);
        return new Result("200","删除成功");
    }


    //--------------------电子书信息表结束

    //------------用户表开始

    @GetMapping("/findAllUser")
    public String users(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<People> peopleList = adminService.findUser();
        List<User> users = new ArrayList<>();
        for (People people : peopleList) {
            String status = adminService.findStatus(people.getStatusId());
            User user = new User(people.getPeopleId(),people.getName(),people.getPhone(),status,people.getAddress());
            users.add(user);
        }
        List<User> pageUser = pageService.findList(users,12,1);
        JSONArray pageUserJson = JSONArray.fromObject(pageUser);
        int allPage = pageService.findAllPage(users,12);
        int haveUser = users.size();
        model.addAttribute("admin",admin);
        model.addAttribute("pageUser",pageUserJson);
        model.addAttribute("allPageUser",allPage);
        model.addAttribute("haveUser",haveUser);
        return "admin/in-admin/用户表";
    }

    @GetMapping("/getNowUser")
    @ResponseBody
    public JSONArray getNowUser(Integer nowPage){
        List<People> peopleList = adminService.findUser();
        List<User> users = new ArrayList<>();
        for (People people : peopleList) {
            String status = adminService.findStatus(people.getStatusId());
            User user = new User(people.getPeopleId(),people.getName(),people.getPhone(),status,people.getAddress());
            users.add(user);
        }
        List<User> pageUser = pageService.findList(users,12,nowPage);
        JSONArray pageUserJson = JSONArray.fromObject(pageUser);
        return pageUserJson;
    }

    @PostMapping("/findUser")
    @ResponseBody
    public JSONArray findUser(People people){
        List<People> peopleList = adminService.findUserByPeople(people);
        if (peopleList==null){
            return null;
        }else {
            List<User> users = new ArrayList<>();
            for (People p : peopleList) {
                if (p==null){
                    return null;
                }
                String status = adminService.findStatus(p.getStatusId());
                User user = new User(p.getPeopleId(),p.getName(),p.getPhone(),status,p.getAddress());
                users.add(user);
            }
            return JSONArray.fromObject(users);
        }
    }


    @GetMapping("/updateUser")
    @ResponseBody
    public Result updateUser(Integer peopleId,Integer statusId){
        People people = adminService.findByPeopleId(peopleId);
        people.setStatusId(statusId);
        adminService.updateByPeopleId(people,peopleId);
        return new Result("200","修改成功");
    }

    @GetMapping("/getPeopleAddress")
    @ResponseBody
    public JSONArray getPeopleAddress(Integer peopleId){
        List<Receiving_address> addresses = adminService.findAllAddress(peopleId);
        if (addresses!=null && addresses.size()>0 && addresses.get(0)!=null){
            return JSONArray.fromObject(addresses);
        }else {
            return null;
        }
    }

    //------------用户表结束

    //--------------所有人员开始
    @GetMapping("/getAllPeople")
    public String getAllPeople(Model model, WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<People> peopleList = adminService.findAllPeople();
        List<People> pagePeople = pageService.findList(peopleList,8,1);
        List<Vip> vip = new ArrayList<>();
        for (People people : pagePeople) {
            if (people.getVipId()==0 || people.getVipId()==-1){
                vip.add(null);
            }else {
                vip.add(adminService.findByVipId(people.getVipId()));
            }
        }
        int allPage = pageService.findAllPage(peopleList,8);
        int havePeople = peopleList.size();
        String PeopleJson = JSONArray.fromObject(pagePeople).toString();
        String VipJson = JSONArray.fromObject(vip).toString();
        // System.out.println(PeopleJson);
        model.addAttribute("admin",admin);
        model.addAttribute("vip",VipJson);
        model.addAttribute("people",PeopleJson);//第一页的json数据
        model.addAttribute("allPeople",allPage);//总共的页数
        model.addAttribute("havePeople",havePeople);//总共的记录数
        return "admin/in-admin/基本信息表(所有人员)";
    }

    @GetMapping("/getNowPeople")
    @ResponseBody
    public Result getNowPeople(Integer nowPage){
        List<People> peopleList = adminService.findAllPeople();
        List<People> pagePeople = pageService.findList(peopleList,8,nowPage);
        List<Vip> vip = new ArrayList<>();
        for (People people : pagePeople) {
            if (people.getVipId()!=null && people.getVipId()!=0){
                vip.add(adminService.findByVipId(people.getVipId()));
            }else {
                vip.add(null);
            }
        }
        String PeopleJson = JSONArray.fromObject(pagePeople).toString();
        String VipJson = JSONArray.fromObject(vip).toString();
        List<String> all = new ArrayList<>();
        all.add(PeopleJson);
        all.add(VipJson);
        return new Result("200","分页成功",all);
    }

    @PostMapping("/findPeople")
    @ResponseBody
    public Result findPeople(People people){
        List<People> peopleList = adminService.findByPeople(people);
        if (peopleList==null || peopleList.size()==0){
            return new Result("404","查询无结果");
        }else {
            List<Vip> vip = new ArrayList<>();
            for (People p : peopleList) {
                if (p!=null && p.getVipId()!=null && p.getVipId()!=0){
                    vip.add(adminService.findByVipId(p.getVipId()));
                }else if (p==null){
                    return new Result("404","查询无结果");
                } else {
                    vip.add(null);
                }
            }
            String PeopleJson = JSONArray.fromObject(peopleList).toString();
            String VipJson = JSONArray.fromObject(vip).toString();
            List<String> all = new ArrayList<>();
            all.add(PeopleJson);
            all.add(VipJson);
            return new Result("200","查询成功",all);

        }

    }

    //--------------所有人员结束

    //--------------公告开始
    @GetMapping("/getAllAnnouncement")
    public String getAllAnnouncement(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Announcement> announcements = adminService.findAllAnnouncement();
        List<Announcement> pageAnnouncements = pageService.findList(announcements,12,1);
        int allPage = pageService.findAllPage(announcements,12);
        int haveAnnouncement = announcements.size();
        String AnnouncementJson = JSONArray.fromObject(pageAnnouncements).toString();
        model.addAttribute("admin",admin);
        model.addAttribute("announcement",AnnouncementJson);
        model.addAttribute("allAnnouncement",allPage);
        model.addAttribute("haveAnnouncement",haveAnnouncement);
        return "admin/in-admin/公告";
    }

    @GetMapping("/getNowAnnouncement")
    @ResponseBody
    public JSONArray getNowAnnouncement(int nowPage){
        List<Announcement> announcements = adminService.findAllAnnouncement();
        List<Announcement> pageAnnouncement = pageService.findList(announcements,12,nowPage);
        JSONArray AnnouncementJson = JSONArray.fromObject(pageAnnouncement);
        return AnnouncementJson;
    }

    @GetMapping("/getAnnouncementInf")
    @ResponseBody
    public String getAnnouncementInf(Integer announcementId){
        Announcement announcement = new Announcement();
        announcement.setAnnouncementId(announcementId);
        Announcement announcement1 = adminService.findByAnnouncement(announcement).get(0);
        String content = announcement1.getContent();
        return content;
    }

    @PostMapping("/findAnnouncement")
    @ResponseBody
    public Result findAnnouncement(Announcement announcement){
        List<Announcement> announcements = adminService.findByAnnouncement(announcement);
        if (announcements!=null){
            if (announcements.size()>0){
                if (announcements.get(0)==null){
                    return new Result("404","查无此结果");
                }else {
                    JSONArray array = JSONArray.fromObject(announcements);
                    return new Result("200","查询成功",array);
                }
            }else {
                return new Result("404","查无此结果");
            }
        }else {
            return new Result("404","查无此结果");
        }
    }

    @GetMapping("/delOneAnnouncement")
    @ResponseBody
    public Result delOneAnnouncement(Integer announcementId){
        adminService.delByAnnouncementId(announcementId);
        return new Result("200","删除成功");
    }

    @PostMapping("/addAnnouncement")
    @ResponseBody
    public Result addAnnouncement(Announcement announcement){
        adminService.addAnnouncement(announcement);
        return new Result("200","添加成功");
    }



    //--------------公告结束

    // ------------书籍类别开始

    @GetMapping("/getAllBookType")
    public String getAllBookType(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<BookType> bookCategoryList = adminService.findAllBookCategory();
        List<BookType> pageBookCategory = pageService.findList(bookCategoryList,12,1);
        int allPage = pageService.findAllPage(bookCategoryList,12);
        int haveBookCategory = bookCategoryList.size();
        String BookCategoryJson = JSONArray.fromObject(pageBookCategory).toString();
        // System.out.println(AdminJson);
        model.addAttribute("admin",admin);
        model.addAttribute("bookCategory",BookCategoryJson);
        model.addAttribute("allBookCategory",allPage);
        model.addAttribute("haveBookCategory",haveBookCategory);
        // System.out.println(BookCategoryJson);
        return "admin/in-admin/书籍类别表";
    }

    @GetMapping("/getNowPageOfBookType")
    @ResponseBody
    public JSONArray getNowPageOfBookType(int nowPage){
        List<BookType> bookCategoryList = adminService.findAllBookCategory();
        List<BookType> pageBookCategory = pageService.findList(bookCategoryList,12,nowPage);
        JSONArray BookCategoryJson = JSONArray.fromObject(pageBookCategory);
        return BookCategoryJson;
    }

    @GetMapping("/searchByBookType")
    @ResponseBody
    public JSONArray searchByBookType(String categoryName){
        BookType bookCategory = adminService.findByCategoryName(categoryName);
        if (bookCategory==null){
            return null;
        }
        List<BookType> bookCategoryList = new ArrayList<>();
        bookCategoryList.add(bookCategory);
        JSONArray BookCategoryJson = JSONArray.fromObject(bookCategoryList);
        return BookCategoryJson;
    }

    //-------------书籍类别结束

    //-------------书籍信息开始

    @GetMapping("/findAllBook")
    public String bookInf(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Books> books = adminService.findAllBook();
        List<Books> pageBooks = pageService.findList(books,7,1);
        List<String> category = new ArrayList<>();
        for (Books pageBook : pageBooks) {
            int typeId = pageBook.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            category.add(name);
        }
        int allPage = pageService.findAllPage(books,7);
        int haveBooks = books.size();
        JSONArray pageBooksJson = JSONArray.fromObject(pageBooks);
        JSONArray categoryJson = JSONArray.fromObject(category);
        model.addAttribute("admin",admin);
        model.addAttribute("books",pageBooksJson);
        model.addAttribute("category",categoryJson);
        model.addAttribute("allBooks",allPage);
        model.addAttribute("haveBooks",haveBooks);
        return "admin/in-admin/书籍信息表";
    }

    @GetMapping("/findOneBook")
    @ResponseBody
    public Books findOneBook(Integer bookId){
        Books books = adminService.findByBookId(bookId);
        return books;
    }

    @GetMapping("/getNowBook")
    @ResponseBody
    public Result getNowBook(Integer nowPage){
        List<Books> books = adminService.findAllBook();
        List<Books> pageBooks = pageService.findList(books,7,nowPage);
        List<String> category = new ArrayList<>();
        for (Books pageBook : pageBooks) {
            int typeId = pageBook.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            category.add(name);
        }

        JSONArray pageBooksJson = JSONArray.fromObject(pageBooks);
        JSONArray categoryJson = JSONArray.fromObject(category);

        List<JSONArray> list = new ArrayList<>();
        list.add(pageBooksJson);
        list.add(categoryJson);
        return new Result("200","分页成功",list);
    }

    @GetMapping("/delOneBook")
    @ResponseBody
    public Result delOneBook(Integer delBookId){
        adminService.delByBkId(delBookId);
        return new Result("200","删除成功");
    }

    @GetMapping("/updateBook")
    @ResponseBody
    public Result updateBook(Integer bookId,Double price){
        adminService.updateBook(bookId,price);
        return new Result("200","修改成功");
    }

    @GetMapping("/updateBookStock")
    @ResponseBody
    public Result updateBookStock(Integer bookId,Integer stock){
        adminService.updateBookStock(bookId,stock);
        return new Result("200","修改成功");
    }

    @PostMapping("/findBook")
    @ResponseBody
    public Result findBook(String title,String author,String category){
        Books books = new Books();
        books.setTitle(title);
        books.setAuthor(author);
        if (category!=null){
            Integer typeId = adminService.findByCategoryName(category).getCategoryId();
            books.setCategoryId(typeId);
        }

        List<String> categorys = new ArrayList<>();
        List<Books> booksList = adminService.findByBook(books);
        for (Books b : booksList) {
            int typeId = b.getCategoryId();
            String name = adminService.findByBookTypeId(typeId).getCategoryName();
            categorys.add(name);
        }

        JSONArray booksListJson = JSONArray.fromObject(booksList);
        JSONArray categoryJson = JSONArray.fromObject(categorys);

        List<JSONArray> list = new ArrayList<>();
        list.add(booksListJson);
        list.add(categoryJson);
        return new Result("200","分页成功",list);

    }

    @PostMapping("/addBook")
    @ResponseBody
    public Result addBook(BookTool bookTool,HttpServletRequest request){
        Integer typeId = adminService.findByCategoryName(bookTool.getCategory()).getCategoryId();
        Books books = new Books(null,bookTool.getTitle(),bookTool.getPrice(),bookTool.getAuthor(),bookTool.getDate(),bookTool.getCompay(),bookTool.getPictureUrl(),bookTool.getDetail(),typeId,bookTool.getStock());
        adminService.addBook(books);
        List<Books> book = adminService.findByBook(books);
        Integer bookId = book.get(0).getBkId();
        String samePath = request.getServletContext().getRealPath("/");
        String path = samePath+"bookImg/"+bookId+".jpg";
        DownloadPicFromUrl.downloadPicture(books.getPictureUrl(),path);
        return new Result("200","添加成功");
    }

    //--------------书籍信息结束

    //-------------vip价格开始

    @GetMapping("/getAllVip")
    public String vip(Model model,WebRequest request){
        String account = request.getParameter("account").trim();
        Admin admin = adminService.findByAccount(account);
        List<Vip> vipList = adminService.findAllVip();
        List<Vip> pageVipList = pageService.findList(vipList,12,1);
        int allPage = pageService.findAllPage(vipList,12);
        int haveVip = vipList.size();
        JSONArray pageVipListJson = JSONArray.fromObject(pageVipList);
        model.addAttribute("admin",admin);
        model.addAttribute("vip",pageVipListJson);
        model.addAttribute("allVip",allPage);
        model.addAttribute("haveVip",haveVip);
        return "admin/in-admin/VIP价格信息表";
    }

    @GetMapping("/getNowPageOfVip")
    @ResponseBody
    public JSONArray getNowPageOfVip(Integer nowPage){
        List<Vip> vipList = adminService.findAllVip();
        List<Vip> pageVipList = pageService.findList(vipList,12,nowPage);
        JSONArray vipJson = JSONArray.fromObject(pageVipList);
        return vipJson;
    }

    @PostMapping("/updateVipPrice")
    @ResponseBody
    public Result updateVipPrice(Integer vipId,Double vipPrice){
        Vip vip = adminService.findByVipId(vipId);
        vip.setVipPrice(vipPrice);
        adminService.updateVip(vip,vipId);
        return new Result("200","修改成功");
    }

    @GetMapping("/findVipByName")
    @ResponseBody
    public JSONArray findVipByName(String vipName){
        List<Vip> vips = adminService.findByVipName(vipName);
        JSONArray vipJson = JSONArray.fromObject(vips);
        return vipJson;
    }

    @PostMapping("/addVip")
    @ResponseBody
    public Result addVip(Vip vip){
        adminService.addVip(vip);
        return new Result("200","添加成功");
    }
    //-------------vip价格结束
}
